package com.tushen;

import org.gdal.gdal.Band;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;
import org.gdal.gdalconst.gdalconst;
import org.gdal.gdalconst.gdalconstConstants;
import org.gdal.ogr.*;
import org.gdal.osr.SpatialReference;
import com.tushen.utils.SqlSessionFactoryUtil;
import com.tushen.utils.Utils;

import java.io.*;
import java.sql.Time;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * create by likun on 2020/7/16 0016
 */
public class UVTask {
    public static void main(String[] args){
        if(args.length==0){
            System.out.println("please input date");
            return;
        }
        String dir="";
        if(args.length>1){
            dir=args[1];
        }

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHH");
        Date dt=null;
        try {
           String str=args[0];
           dt=  simpleDateFormat.parse(str);

        }catch (Exception e){
            e.printStackTrace();
        }
//
//        String shpPath=dir+"\\dye.shp";
////        String shpPath ="E:\\test\\test.shp";
        String tifPath=dir+"dye.tiff";
        String pathLont=dir+"x.csv";
        String pathLat=dir+"y.csv";
        String pathNv=dir+"nv.csv";
        String pathU=dir+"u.csv";
        String pathV=dir+"v.csv";
        String dstUVDir=dir+"dstuv";
        String pathDye=dir+"dye.csv";
        String dstDir=dir+"dstdye";
        String src="D:\\dstdye\\dyetif2";
        String dst="D:\\dstdye\\dyetif3";
//        createDyeTif(tifPath,pathLont,pathLat,pathDye);
//        createShpFile(shpPath,pathLont,pathLat,pathDye);
        Calendar calendar=Calendar.getInstance();
//        calendar.set(2020,6,1,16,0,0);
//        calendar.set(2020,3,25,0,0,0);
        calendar.setTime(dt);

        //处理dye浓度数据
        prcossDyePoint(calendar,pathLont,pathLat,pathDye,dstDir);

        //读取uv数据，并生成三角网shp
//        prcossUVTriangle(calendar,pathLont,pathLat,pathNv,pathU,pathV,dstUVDir);

        // 静态三角网顶点shp生成
        File file=new File(dstUVDir);
        if(!file.exists()){
            file.mkdir();
        }
        createTrianglePointShp(pathLont,pathLat,dstUVDir);
        // 静态三角网shp生成
        createTriangleShp(pathLont,pathLat,pathNv,dstUVDir);
//        interpolateToTiff();
       // readNameTif("D:\\dstdye\\dyetif3");
//        readNameTif("D:\\dstdye\\dyetif3");
//        setGDALNoDataValue("D:\\dstdye\\dyetif");
//        calCatUVView();
//        moveNameTif(src,dst);


    }


    /**
     * shp 浓度点空间插值生成tif
      */
   public static void  interpolateToTiff(){
//        File file=new File("D:\\dstdye");
        File file=new File("D:\\dstdye\\2020070100\\dstdye");
        File[] files=file.listFiles();
        for (int i=0;i<files.length;i++){
            if(files[i].getName().endsWith("shp")){
//                String conmand="gdal_grid -zfield dye  -of GTiff -ot Float32  -txe 105.59500926 109.94270074 -tye 16.13244326 21.91781758 -outsize 251 334 -l" +
                  String conmand="gdal_grid -zfield dye  -of GTiff -ot Float32  -outsize 502 668 -l" +
//                  String conmand="gdal_grid -zfield \"dye\" -of GTiff -ot Float16  -txe 105.59500926 109.94270074 -tye 16.13244326 21.91781758 -outsize 251 334 -l" +
                        " "+files[i].getName().replace(".shp","")+" -a invdist:power=2.0:radius1=0.0062148:radius2=0.0062148:max_points=12 "
//                          +files[i].getAbsolutePath()+" D:\\dstdye\\dyetif\\"+files[i].getName().replace(".shp",".tif");
                +files[i].getAbsolutePath()+" D:\\dstdye\\2020070100\\gdaltif\\"+files[i].getName().replace(".shp",".0.tif");
//                if(!files[i].getName().contains("202005070700-")){
              if(!files[i].getName().contains("202007081600")){
                    continue;
                }
                System.out.println(conmand);
                try {
                    runCMD(conmand);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
   }

    /**
     * 设置tif的nodatavalue
     * @param dir
     */
    public static void setGDALNoDataValue(String dir) {
        gdal.AllRegister();
        //读取影像数据
        File fileDir=new File(dir);
        File[] files=fileDir.listFiles();
        for (int i=0;i<files.length;i++){

            if(!files[i].getName().contains("202005070700")){
                continue;
            }
            System.out.println(i);
            String fileName=files[i].getAbsolutePath();
            Dataset dataset = gdal.Open(fileName, gdalconstConstants.GA_Update);
            Band band = dataset.GetRasterBand(1);
            band.SetNoDataValue(0.00000);
            band.delete();
            dataset.delete();
        }

        gdal.GDALDestroyDriverManager();
    }

   //重命名文件tif
   public static void readNameTif(String dir){
       File fileDir=new File(dir);
       File[] files=fileDir.listFiles();
       for (int i=0;i<files.length;i++){
//           if(!files[i].getName().contains("202005070700-")){
//               continue;
//           }
          String elevation= files[i].getName().split("-")[1].replace(".tif","");
          String dtm=files[i].getName().split("-")[0];
           String eleFix=new DecimalFormat("00.0").format(Double.parseDouble(elevation));
           String newFileName=dir+"\\"+dtm+"_"+eleFix+".tif";
           File file=new File(newFileName);
           files[i].renameTo(file);
       }
   }

    //移动文件tif
    public static void moveNameTif(String src,String dst){
        File fileDir=new File(src);
        File[] files=fileDir.listFiles();
        for (int i=0;i<files.length;i++){
            if(!files[i].getName().endsWith("tif")){
                continue;
            }

            String newFileName=dst+"\\"+files[i].getName();
//            System.out.println(files[i].getName());
//            System.out.println(newFileName);
           Utils.copy(files[i].getAbsolutePath(),newFileName);
        }
    }



   //表层流场分级切片提取用于快速显示
   public static void calCatUVView(){
       for (int i=1;i<170;i++){
          System.out.println(i);
          String sql="insert into uv_nc_shp_layer\n" +
                  "SELECT to_date (substring(filename,9,10),'yyyyMMddHH24') as dt,\n" +
                  "to_timestamp (substring(filename,9,10),'yyyyMMddHH24')::time(0) as tm,\n" +
                  "u,v,x,y,geom,\n" +
                  "case when x%40=0 and y%40=0 then 1\n" +
                  " when x%20=0 and y%20=0 then 2\n" +
                  " when x%10=0 and y%10=0 then 3 else  4 end as class \n" +
                  "\n" +
                  "\n" +
                  "\tFROM (SELECT filename, u.geom,u.x,u.y,u.val as u,v.val as v \n" +
                  "\t\t  FROM (select * from uv_nctif2 where rid="+i+") as s, \n" +
                  "\t\t  LATERAL ST_PixelAsCentroids(rast, 1) AS u,\n" +
                  "\t\t  LATERAL ST_PixelAsCentroids(rast, 2) AS v\n" +
                  "\t\t  WHERE (  (u.x%40=0 and u.y%40=0) or \n" +
                  "\t\t\t\t\t\t\t(u.x%20=0 and u.y%20=0) or (u.x%10=0 and u.y%10=0)\n" +
                  "\t\t\t\tor (u.x%5=0 and u.y%5=0))\n" +
                  "\t\t  and u.x=v.x and u.y=v.y  ) foo;";
          SqlSessionFactoryUtil.excuteQuerySql(sql);
          System.out.println(new Date().toString()+"\n");

       }
   }

   //执行cmd命令
    public static boolean runCMD(String cmd) throws IOException, InterruptedException, IOException {
        final String METHOD_NAME = "runCMD";
        Process p = Runtime.getRuntime().exec(cmd);
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String readLine = br.readLine();
            StringBuilder builder = new StringBuilder();
            while (readLine != null) {
                readLine = br.readLine();
                builder.append(readLine);
            }
            System.out.println(METHOD_NAME + "#readLine: " + builder.toString());

            p.waitFor();
            int i = p.exitValue();
            System.out.println(METHOD_NAME + "#exitValue = " + i);
            if (i == 0) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            System.out.println(METHOD_NAME + "#ErrMsg=" + e.getMessage());
            e.printStackTrace();
            throw e;
        } finally {
            if (br != null) {
                br.close();
            }
        }
    }

   //读取dye数据，并生成点shp
   public static void prcossDyePoint(Calendar calendar, String pathLont, String pathLat, String pathDye,String dstDir){

       double[][] lonts = Utils.readTxtToArray(pathLont);
       double[][] lats = Utils.readTxtToArray(pathLat);
       try {
           File file = new File(pathDye);
           String encoding = "UTF-8";
           if (file.isFile() && file.exists()) {
               InputStreamReader read = new InputStreamReader(
                       new FileInputStream(file), encoding);
               BufferedReader bufferedReader = new BufferedReader(read);
               String lineTxt = "";
               int layer=1;
               int tm=1;
               while ((lineTxt = bufferedReader.readLine()) != null) {
                   if(lineTxt.length()==0){
                       layer=1;
                       tm++;
                       calendar.add(Calendar.HOUR,1);
                       continue;
                   }

                   String[] myArray=lineTxt.trim().split(",");
                   List<Double> lineList = new ArrayList<Double>();
                   for (String str : myArray) {
                       double dye=Math.abs(Double.parseDouble(str));
                       lineList.add(dye);
                   }
//                   createDyeShp(calendar,layer,lonts[0],lats[0],lineList,dstDir);
                   dumpDyeShp(calendar,layer,lineList,dstDir);
                   layer++;

               }
               read.close();

           } else {
               System.out.println("文件不存在!！");
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

   // 生成点shp
   private static void createDyeShp(Calendar calendar,int layer,double[] lonts,double[] lats,List<Double> dye,String dstDir){

       SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmm");
       String eleFix=new DecimalFormat("00").format(layer);
       String shpPath=dstDir+"\\"+simpleDateFormat.format(calendar.getTime())+"_"+eleFix+".shp";

       ogr.RegisterAll();
       gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");//路径中支持中文
       gdal.SetConfigOption("SHAPE_ENCODING", "CP936");// shp属性中支持中文
//        gdal.SetConfigOption("GDAL_DATA","D:\\release-1900-x64-gdal-3-0-2-mapserver-7-4-2\\bin\\gdal-data");

       String strDriverName = "ESRI Shapefile";
       org.gdal.ogr.Driver oDriver = ogr.GetDriverByName(strDriverName);
       if (oDriver == null) {
           System.out.println(shpPath + " 驱动不可用！\n");
           return;
       }
       DataSource oDS = oDriver.CreateDataSource(shpPath, null);
       if (oDS == null) {
           System.out.println("创建矢量文件【" + shpPath + "】失败！\n");
           return;
       }



       // 创建图层，创建一个多边形图层，这里没有指定空间参考，如果需要的话，需要在这里进行指定
       //如果是mif或者tab，其实是可以多元素混合存放的，shp每个图层只能存放点线面中的一种。
       //所以tab创建图层的时候，选择什么都不影响后面的操作和存储结果
       SpatialReference spatialReference = new SpatialReference();
       spatialReference.ImportFromEPSG(4326);

       Layer oLayer =oDS.CreateLayer("TestPoint", spatialReference, ogr.wkbPoint, null);
       if (oLayer == null) {
           System.out.println("图层创建失败！\n");
           return;
       }

       // 先创建一个叫FieldID的整型属性
       FieldDefn oFieldID = new FieldDefn("dye", ogr.OFTReal);
       oLayer.CreateField(oFieldID, 1);

       FeatureDefn oDefn = oLayer.GetLayerDefn();

       System.out.println(shpPath+" read finish");
       for (int i=0;i<lonts.length;i++){
               if(dye.get(i)==0)continue;
               Feature oFeatureTriangle = new Feature(oDefn);
               oFeatureTriangle.SetField(0, dye.get(i));
               Geometry geomTriangle = Geometry.CreateFromWkt("POINT ("+lonts[i]+" "+lats[i]+")");
               oFeatureTriangle.SetGeometry(geomTriangle);
               oLayer.CreateFeature(oFeatureTriangle);
       }

       oDS.SyncToDisk();
       System.out.println("数据集创建完成！");
   }


    // dye 浓度入库方式2
    private static void dumpDyeShp(Calendar calendar,int layer,List<Double> dye,String dstDir){

        calendar.set(Calendar.MILLISECOND,0);
        ArrayList<HashMap> list=new ArrayList<HashMap>();
        java.sql.Date dt=new java.sql.Date(calendar.getTime().getTime());
        Time tm=new java.sql.Time(calendar.getTime().getTime());

//        System.out.println(tm);
//        if(true)return;
        try {
        for (int i=0;i<dye.size();i++){


            if(dye.get(i)==0)continue;

            HashMap map=new HashMap();
            map.put("dt",dt);
            map.put("tm",tm);
            map.put("layer",layer);
            map.put("id",i);
            map.put("dye",dye.get(i));


            list.add(map);
            if(list.size()>=20000){
                SqlSessionFactoryUtil.dumpPGDatalist(list,"dye_shp_result");
                list.clear();
              }
         }
         SqlSessionFactoryUtil.dumpPGDatalist(list,"dye_shp_result");

        }catch (Exception e){
            e.printStackTrace();
        }


    }


    //读取uv数据，并生成三角网shp
    public static void prcossUVTriangle(Calendar calendar, String pathLont, String pathLat,String pathNv,String pathU,String pathV,String dstDir){

        double[][] lonts = Utils.readTxtToArray(pathLont);
        double[][] lats = Utils.readTxtToArray(pathLat);
        int[][] nv = Utils.readTxtToArrayIntenger(pathNv);
        try {
            File fileU = new File(pathU);
            File fileV = new File(pathV);
            String encoding = "UTF-8";
            if (fileU.isFile() && fileU.exists()&&fileV.isFile() && fileV.exists()) {
                InputStreamReader readU = new InputStreamReader(
                        new FileInputStream(fileU), encoding);
                InputStreamReader readV = new InputStreamReader(
                        new FileInputStream(fileV), encoding);
                BufferedReader bufferedReaderU = new BufferedReader(readU);
                BufferedReader bufferedReaderV = new BufferedReader(readV);
                String lineTxtU = "";
                String lineTxtV = "";
                int layer=1;
                int tm=1;
                while ((lineTxtU = bufferedReaderU.readLine()) != null&&(lineTxtV = bufferedReaderV.readLine()) != null) {
                    if(lineTxtU.length()==0){
                        layer=1;
                        tm++;
                        calendar.add(Calendar.HOUR,1);
                        System.out.println("时刻:"+tm);
                        continue;
                    }

                    String[] myArrayU=lineTxtU.trim().split(",");
                    String[] myArrayV=lineTxtV.trim().split(",");
                    List<Double> lineListU = new ArrayList<Double>();
                    List<Double> lineListV = new ArrayList<Double>();
                    for (String str : myArrayU) {
                        lineListU.add(Double.parseDouble(str));
                    }
                    for (String str : myArrayV) {
                        lineListV.add(Double.parseDouble(str));
                    }

                    createUVShp(calendar,layer,lonts[0],lats[0],nv,lineListU,lineListV,dstDir);
                    dumpUVData(calendar,layer,lineListU,lineListV);

                    layer++;

                }
                readU.close();
                readV.close();

            } else {
                System.out.println("文件不存在!！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //将uv结果入到数据库-处理方式一
    private static void dumpUVData(Calendar calendar,int layer,List<Double> lineListU,List<Double> lineListV){
        ArrayList<HashMap> list=new ArrayList<HashMap>();

        SimpleDateFormat simpleDateFormat1=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat2=new SimpleDateFormat(" HH:mm:ss");
        java.sql.Date dt=new java.sql.Date(calendar.getTime().getTime());
        Time tm=new java.sql.Time(calendar.getTime().getTime());
        try {
        for (int i=0;i<lineListU.size();i++){
            HashMap map=new HashMap();
            map.put("dt",dt);
            map.put("tm",tm);
            map.put("layer",layer);
            map.put("id",i);
            double u=lineListU.get(i);
            double v=lineListV.get(i);
            double direction=Utils.getDirection(u,v);
            double speed=Math.sqrt(u*u+v*v);
            map.put("u",direction);
            map.put("v",speed);
            list.add(map);
            if(list.size()>=20000){
                SqlSessionFactoryUtil.dumpPGDatalist(list,"uv_shp_result");
                list.clear();
            }
        }
            SqlSessionFactoryUtil.dumpPGDatalist(list,"uv_shp_result");
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    // 生成带uv的三角网shp--处理方式二
    private static void createUVShp(Calendar calendar,int layer,double[] lonts,double[] lats,int[][] nv,List<Double> U,List<Double> V,String dstDir){

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmm");
        String shpPath=dstDir+"\\"+simpleDateFormat.format(calendar.getTime())+"-"+layer+".shp";

        ogr.RegisterAll();
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");//路径中支持中文
        gdal.SetConfigOption("SHAPE_ENCODING", "CP936");// shp属性中支持中文
//        gdal.SetConfigOption("GDAL_DATA","D:\\release-1900-x64-gdal-3-0-2-mapserver-7-4-2\\bin\\gdal-data");

        String strDriverName = "ESRI Shapefile";
        org.gdal.ogr.Driver oDriver = ogr.GetDriverByName(strDriverName);
        if (oDriver == null) {
            System.out.println(shpPath + " 驱动不可用！\n");
            return;
        }
        DataSource oDS = oDriver.CreateDataSource(shpPath, null);
        if (oDS == null) {
            System.out.println("创建矢量文件【" + shpPath + "】失败！\n");
            return;
        }



        // 创建图层，创建一个多边形图层，这里没有指定空间参考，如果需要的话，需要在这里进行指定
        //如果是mif或者tab，其实是可以多元素混合存放的，shp每个图层只能存放点线面中的一种。
        //所以tab创建图层的时候，选择什么都不影响后面的操作和存储结果
        SpatialReference spatialReference = new SpatialReference();
        spatialReference.ImportFromEPSG(4326);

        Layer oLayer =oDS.CreateLayer("TestPoint", spatialReference, ogr.wkbPolygon, null);
        if (oLayer == null) {
            System.out.println("图层创建失败！\n");
            return;
        }

        // 先创建一个叫FieldID的整型属性
        FieldDefn oFieldIDU = new FieldDefn("u", ogr.OFTReal);
        oLayer.CreateField(oFieldIDU);
        FieldDefn oFieldIDV = new FieldDefn("v", ogr.OFTReal);
        oLayer.CreateField(oFieldIDV);

        FeatureDefn oDefn = oLayer.GetLayerDefn();

        System.out.println("read finish");

        for (int i=0;i<nv[0].length;i++){
            Feature oFeatureTriangle = new Feature(oDefn);
            oFeatureTriangle.SetField(0, U.get(i));
            oFeatureTriangle.SetField(1, V.get(i));

            int a=nv[0][i]-1;
            int b=nv[1][i]-1;
            int c=nv[2][i]-1;
            Geometry geomTriangle = Geometry.CreateFromWkt("POLYGON (("+lonts[a]+" "+lats[a]+","+lonts[b]+" "+lats[b]+
                    ","+lonts[c]+" "+lats[c]+","+lonts[a]+" "+lats[ a]+"))");
            oFeatureTriangle.SetGeometry(geomTriangle);
            oLayer.CreateFeature(oFeatureTriangle);
        }

//        String strTifDriverName = "GTiff";
//        org.gdal.gdal.Driver oTifDriver = gdal.GetDriverByName(strTifDriverName);
//        String tifPath=dstDir+"\\"+simpleDateFormat.format(calendar.getTime())+"-"+layer+".tif";
//        if (oDriver == null) {
//            System.out.println(strDriverName + " 驱动不可用！\n");
//            return;
//        }
//        Dataset dataset = oTifDriver.Create(tifPath, 400, 450, 1, gdalconst.GDT_Float32);
//
//        gdal.RasterizeLayer(dataset,new int[]{1},oLayer);

        oDS.SyncToDisk();
        System.out.println("数据集创建完成！");
    }

    // 生成静态三角shp文件
    public static void createTriangleShp(String pathLont, String pathLat, String pathNv,String dstDir){
        double[][] lonts = Utils.readTxtToArray(pathLont);
        double[][] lats = Utils.readTxtToArray(pathLat);
        int[][] nv = Utils.readTxtToArrayIntenger(pathNv);
       ogr.RegisterAll();
       gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");//路径中支持中文
       gdal.SetConfigOption("SHAPE_ENCODING", "CP936");// shp属性中支持中文
//        gdal.SetConfigOption("GDAL_DATA","D:\\release-1900-x64-gdal-3-0-2-mapserver-7-4-2\\bin\\gdal-data");
       String shpPath=dstDir+"\\uv_shp_polygon.shp";
       String strDriverName = "ESRI Shapefile";
       org.gdal.ogr.Driver oDriver = ogr.GetDriverByName(strDriverName);
       if (oDriver == null) {
           System.out.println(shpPath + " 驱动不可用！\n");
           return;
       }
       DataSource oDS = oDriver.CreateDataSource(shpPath, null);
       if (oDS == null) {
           System.out.println("创建矢量文件【" + shpPath + "】失败！\n");
           return;
       }

       // 创建图层，创建一个多边形图层，这里没有指定空间参考，如果需要的话，需要在这里进行指定
       //如果是mif或者tab，其实是可以多元素混合存放的，shp每个图层只能存放点线面中的一种。
       //所以tab创建图层的时候，选择什么都不影响后面的操作和存储结果
       SpatialReference spatialReference = new SpatialReference();
       spatialReference.ImportFromEPSG(4326);

       Layer oLayer =oDS.CreateLayer("TestPoint", spatialReference, ogr.wkbPolygon, null);
       if (oLayer == null) {
           System.out.println("图层创建失败！\n");
           return;
       }

       // 先创建一个叫FieldID的整型属性
       FieldDefn oFieldID = new FieldDefn("id", ogr.OFTInteger);
       oLayer.CreateField(oFieldID, 1);

       FeatureDefn oDefn = oLayer.GetLayerDefn();

       System.out.println("read finish");
       for (int i=0;i<nv[0].length;i++){
           Feature oFeatureTriangle = new Feature(oDefn);
           oFeatureTriangle.SetField(0,i);

           int a=nv[0][i]-1;
           int b=nv[1][i]-1;
           int c=nv[2][i]-1;
           Geometry geomTriangle = Geometry.CreateFromWkt("POLYGON (("+lonts[0][ a]+" "+lats[0][a]+","+lonts[0][b]+" "+lats[0][b]+
                   ","+lonts[0][c]+" "+lats[0][c]+","+lonts[0][a]+" "+lats[0][a]+"))");
           oFeatureTriangle.SetGeometry(geomTriangle);
           oLayer.CreateFeature(oFeatureTriangle);
       }

       oDS.SyncToDisk();
       System.out.println("数据集创建完成！");
   }


    // 生成静态三角顶点shp文件
    public static void createTrianglePointShp(String pathLont, String pathLat,String dstDir){
        double[][] lonts = Utils.readTxtToArray(pathLont);
        double[][] lats = Utils.readTxtToArray(pathLat);
        ogr.RegisterAll();
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");//路径中支持中文
        gdal.SetConfigOption("SHAPE_ENCODING", "CP936");// shp属性中支持中文
//        gdal.SetConfigOption("GDAL_DATA","D:\\release-1900-x64-gdal-3-0-2-mapserver-7-4-2\\bin\\gdal-data");
        String shpPath=dstDir+"\\dye_shp_point.shp";
        String strDriverName = "ESRI Shapefile";
        org.gdal.ogr.Driver oDriver = ogr.GetDriverByName(strDriverName);
        if (oDriver == null) {
            System.out.println(shpPath + " 驱动不可用！\n");
            return;
        }
        DataSource oDS = oDriver.CreateDataSource(shpPath, null);
        if (oDS == null) {
            System.out.println("创建矢量文件【" + shpPath + "】失败！\n");
            return;
        }

        // 创建图层，创建一个多边形图层，这里没有指定空间参考，如果需要的话，需要在这里进行指定
        //如果是mif或者tab，其实是可以多元素混合存放的，shp每个图层只能存放点线面中的一种。
        //所以tab创建图层的时候，选择什么都不影响后面的操作和存储结果
        SpatialReference spatialReference = new SpatialReference();
        spatialReference.ImportFromEPSG(4326);

        Layer oLayer =oDS.CreateLayer("TestPoint", spatialReference, ogr.wkbPoint, null);
        if (oLayer == null) {
            System.out.println("图层创建失败！\n");
            return;
        }

        // 先创建一个叫FieldID的整型属性
        FieldDefn oFieldID = new FieldDefn("id", ogr.OFTInteger);
        oLayer.CreateField(oFieldID, 1);

        FeatureDefn oDefn = oLayer.GetLayerDefn();

        System.out.println("read finish");
        for (int i=0;i<lonts[0].length;i++){
            Feature oFeatureTriangle = new Feature(oDefn);
            oFeatureTriangle.SetField(0, i);
            Geometry geomTriangle = Geometry.CreateFromWkt("POINT ("+lonts[0][i]+" "+lats[0][i]+")");
            oFeatureTriangle.SetGeometry(geomTriangle);
            oLayer.CreateFeature(oFeatureTriangle);
        }

        oDS.SyncToDisk();
        System.out.println("数据集创建完成！");
    }

   public static void createShpFile(String shpPath,String pathLont,String pathLat,String pathDye) {

        ogr.RegisterAll();
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");//路径中支持中文
        gdal.SetConfigOption("SHAPE_ENCODING", "CP936");// shp属性中支持中文
//        gdal.SetConfigOption("GDAL_DATA","D:\\release-1900-x64-gdal-3-0-2-mapserver-7-4-2\\bin\\gdal-data");

        String strDriverName = "ESRI Shapefile";
        org.gdal.ogr.Driver oDriver = ogr.GetDriverByName(strDriverName);
        if (oDriver == null) {
            System.out.println(shpPath + " 驱动不可用！\n");
            return;
        }
        DataSource oDS = oDriver.CreateDataSource(shpPath, null);
        if (oDS == null) {
            System.out.println("创建矢量文件【" + shpPath + "】失败！\n");
            return;
        }



       // 创建图层，创建一个多边形图层，这里没有指定空间参考，如果需要的话，需要在这里进行指定
       //如果是mif或者tab，其实是可以多元素混合存放的，shp每个图层只能存放点线面中的一种。
       //所以tab创建图层的时候，选择什么都不影响后面的操作和存储结果
       SpatialReference spatialReference = new SpatialReference();
       spatialReference.ImportFromEPSG(4326);

       Layer oLayer =oDS.CreateLayer("TestPoint", spatialReference, ogr.wkbPoint, null);
       if (oLayer == null) {
           System.out.println("图层创建失败！\n");
           return;
       }


       // 下面创建属性表
       // 先创建一个叫FieldID的整型属性
       FieldDefn oFieldID = new FieldDefn("FieldID", ogr.OFTReal);
       oLayer.CreateField(oFieldID, 1);

       FeatureDefn oDefn = oLayer.GetLayerDefn();

       double[][] lonts = Utils.readTxtToArray(pathLont);
       double[][] lats = Utils.readTxtToArray(pathLat);

       double[][] dye=Utils.readTxtToArray2(pathDye);

       System.out.println("read finish");
       for (int i=0;i<dye.length;i++){
           for (int j=0;j<dye[i].length;j++){

//               if(dye[i][j]==0)continue;
               Feature oFeatureTriangle = new Feature(oDefn);
               oFeatureTriangle.SetField(0, dye[i][j]);
               Geometry geomTriangle = Geometry.CreateFromWkt("POINT ("+lonts[0][j]+" "+lats[0][j]+")");
               oFeatureTriangle.SetGeometry(geomTriangle);
               oLayer.CreateFeature(oFeatureTriangle);
           }
           break;
       }





        oDS.SyncToDisk();
        System.out.println("\n数据集创建完成！\n");
    }

    public static void createDyeTif(String tifPath,String pathLont,String pathLat,String pathDye) {
        gdal.AllRegister();
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
        //gdal.SetConfigOption("SHAPE_ENCODING","CP936");

        SpatialReference ref = new SpatialReference();
        ref.SetWellKnownGeogCS("WGS84");

        ref.ExportToWkt();// 可配置String数组 defWkt
        String strDriverName = "GTiff";
        org.gdal.gdal.Driver oDriver = gdal.GetDriverByName(strDriverName);
        if (oDriver == null) {
            System.out.println(strDriverName + " 驱动不可用！\n");
            return;
        }

        double[][] lonts = Utils.readTxtToArray(pathLont);
        double[][] lats = Utils.readTxtToArray(pathLat);


        double lontMin = Arrays.stream(lonts[0]).min().getAsDouble();
        double lontMax = Arrays.stream(lonts[0]).max().getAsDouble();
        double latMax = Arrays.stream(lats[0]).max().getAsDouble();
        double latMin = Arrays.stream(lats[0]).min().getAsDouble();

        double intervalLont = (lontMax - lontMin) / (lonts[0].length - 1);
        double intervalLat = (latMax - latMin) / (lats[0].length - 1);
        // @param double[] argin  地理坐标 米转经纬度单位
        // 0:左上角x坐标 1:东西方向空间分辨率 2:x方向旋转角0° 3:左上角y坐标 4:y方向旋转角0° 5:南北方向空间分辨率
        double[] argin = {lontMin, intervalLont, 0, latMax, 0, -intervalLat};
        Dataset dataset = oDriver.Create(tifPath, lonts[0].length, lats[0].length, 1, gdalconst.GDT_Float32);
        dataset.SetGeoTransform(argin);
        dataset.SetSpatialRef(ref);
        // @param int xoff(偏移量), int yoff, int xsize, int ysize, int buf_type, byte[] array
        Band band = dataset.GetRasterBand(1);// 波段  (色彩)
        double[][] txtArray = Utils.readTxtToArray(pathDye);
        float[] arr = new float[450 * 600];
        int c = 0;
        for (int j = 0; j < 450 /*txtArray.length*/; j++) {
            for (int j2 = 0; j2 < 600/*txtArray[j].length*/; j2++) {
                if (txtArray[j][j2] > 0) {
                    arr[c] = (float) txtArray[j][j2];
                } else {
//                    arr[c] =null;
                }

                c++;
            }
        }
    }



    public static double[][] readTxtToArray(String path) {
        List<List<Double>> conList = new ArrayList<List<Double>>();
        double[][] douline = null;
        try {
            File file = new File(path);
            String encoding = "UTF-8";
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = "";
                int len = 0;
                int emptyLine=0;
                int interval=0;
                while ((lineTxt = bufferedReader.readLine()) != null) {
//                    System.out.println(lineTxt);
                    String[] myArray=lineTxt.trim().replaceAll("\\s+",",").split(",");
//                    if(myArray.length==1){
//                        System.out.println(myArray[0]);
//                    }
                    if(myArray.length>1){
//                        System.out.println(myArray.length);
                        interval++;
                    }else if(myArray.length==1){
                        System.out.println(lineTxt);
                        emptyLine++;
                        len++;
                        System.out.println("interval:"+interval);
                        System.out.println("len:"+len);
                        interval=0;
                        continue;
                    }
                    int kk=0;
                    List<Double> lineList = new ArrayList<Double>();
                    for (String str : myArray) {
                        if(str.length()>0){
                            double ss=Double.parseDouble(str);
//                            lineList.add(ss);
                            if(ss>0){
//                                System.out.println(ss);
                                kk++;
                            }
                        }

                    }
                    System.out.println("kk="+kk);
                    conList.add(lineList);
//                    if(len>10)break;
                    len++;
                }
                System.out.println("len="+len);
                System.out.println("emptyLine="+emptyLine);
                read.close();
                douline = new double[conList.size()][conList.get(0).size()];
                for (int i = 0; i <conList.size(); i++) {
                    for (int j = 0; j < conList.get(i).size(); j++) {
                        if(!conList.get(i).isEmpty()&&conList.get(i).size()!=0){
                            douline[i][j]=conList.get(i).get(j);
                        }
                    }
                }
            } else {
                System.out.println("文件不存在!！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return douline;
    }
}
